<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级菜单" prop="parentId">
          <el-cascader
            class="data-cascader"
            v-model="form.parentId"
            :options="menuOptions"
            :props="menuProps"
            placeholder="请选择"
            :show-all-levels="false"
            clearable
            :disabled="!!form.pkid"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <el-radio-group v-model="form.menuType">
            <el-radio
              v-for="(item, index) of dict['menuType']"
              :key="index"
              :value="item.value"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="catalogName">
          <el-input
            class="data-input"
            v-model="form.catalogName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜单编码" prop="code">
          <el-input
            class="data-input"
            v-model="form.code"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="路由地址"
          prop="routePath"
          v-if="form.menuType === '0'"
        >
          <el-input
            class="data-input"
            v-model="form.routePath"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="路由组件"
          prop="routeModule"
          v-if="form.menuType === '0'"
        >
          <el-input
            class="data-input"
            v-model="form.routeModule"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="显示状态"
          prop="showStatus"
          v-if="form.menuType === '0'"
        >
          <el-radio-group v-model="form.showStatus">
            <el-radio
              v-for="(item, index) of dict['yn']"
              :key="index"
              :value="Number(item.value)"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单状态" prop="status">
          <el-radio-group
            v-model="form.status"
            :disabled="form.children && form.children.length > 0"
          >
            <el-radio
              v-for="(item, index) of dict['status']"
              :key="index"
              :value="Number(item.value)"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="菜单图标"
          prop="choosePicture"
          v-if="form.menuType === '0'"
        >
          <el-upload
            action=""
            :on-change="
              (file, fileList) => getFile(file, fileList, 'choosePicture')
            "
            :on-remove="
              (file, fileList) => handleRemove(file, fileList, 'choosePicture')
            "
            :limit="1"
            accept=".png, .jpg, .jepg"
            list-type="picture-card"
            :auto-upload="false"
            class="custom-upload"
            :file-list="fileList1"
          >
            <el-button size="small" type="primary" v-if="!form.choosePicture"
              ><el-icon><Plus /></el-icon
            ></el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="菜单选中图标"
          prop="chooseSvgPicture"
          v-if="form.menuType === '0'"
        >
          <el-upload
            action=""
            :on-change="
              (file, fileList) => getFile(file, fileList, 'chooseSvgPicture')
            "
            :on-remove="
              (file, fileList) =>
                handleRemove(file, fileList, 'chooseSvgPicture')
            "
            :limit="1"
            accept=".png, .jpg, .jepg"
            list-type="picture-card"
            :auto-upload="false"
            class="custom-upload custom-upload-dark"
            :file-list="fileList2"
          >
            <el-button size="small" type="primary" v-if="!form.chooseSvgPicture"
              ><el-icon><Plus /></el-icon
            ></el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useDict } from '@/hooks/useDict'
import { menuAdd, getMenuList } from '@/api/manager/systemManage/menu.js'
const { dict, initListDictOptions } = useDict(['status', 'menuType', 'yn'])
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  () => {
    if (props.detail.pkid) {
      form.value = { ...props.detail }
      if (props.detail.choosePicture) {
        fileList1.value = [
          {
            name: 'name',
            uid: '1',
            url: props.detail.choosePicture,
          },
        ]
      }
      if (props.detail.chooseSvgPicture) {
        fileList2.value = [
          {
            name: 'name',
            uid: '1',
            url: props.detail.chooseSvgPicture,
          },
        ]
      }
    } else {
      form.value.parentId = props.detail.parentId
    }
  },
)
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
watch(
  () => dialogVisible.value,
  () => {
    if (dialogVisible.value) {
      initMenuOption()
    }
  },
)
const handleClose = (isFlase) => {
  form.value = {
    orderIndex: 1,
    status: 1,
    showStatus: 1,
    menuType: '0',
    choosePicture: '',
    chooseSvgPicture: '',
  }
  fileList1.value = []
  fileList2.value = []
  dialogVisible.value = false
  emit('close', isFlase)
}
const formRef = ref(null)
const form = ref({
  orderIndex: 1,
  status: 1,
  showStatus: 1,
  menuType: '0',
})
const rules = ref({
  // parentId: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
  menuType: [{ required: true, message: '请选择菜单类型', trigger: 'blur' }],
  orderIndex: [{ required: true, message: '请输入显示排序', trigger: 'blur' }],
  routePath: [{ required: true, message: '请输入路由地址', trigger: 'blur' }],
  // routeModule: [{ required: true, message: '请输入组件地址', trigger: 'blur' }],
  code: [{ required: true, message: '请输入菜单编码', trigger: 'blur' }],
  catalogName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  showStatus: [{ required: true, message: '请选择显示状态', trigger: 'blur' }],
  status: [{ required: true, message: '请选择菜单状态', trigger: 'blur' }],
})
const fileList1 = ref([])
const fileList2 = ref([])
const menuProps = ref({
  expandTrigger: 'hover',
  value: 'pkid',
  label: 'catalogName',
  children: 'children',
  checkStrictly: true,
  emitPath: false,
})
const menuOptions = ref([])
const initMenuOption = async () => {
  const res = await getMenuList()
  if (res.success) {
    menuOptions.value = res.data[0].children
  } else {
    ElMessage.error(res.message)
  }
}
const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = { ...form.value }
      if (!params.pkid && !params.parentId) {
        params.parentId = 'menu'
      }
      delete params.children
      try {
        const res = await menuAdd(params)
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}

const getFile = (file, fileList, key) => {
  getBase64(file.raw).then((res) => {
    form.value[key] = res
  })
}
const getBase64 = (file) => {
  return new Promise(function (resolve, reject) {
    let reader = new FileReader()
    let imgResult = ''
    reader.readAsDataURL(file)
    reader.onload = function () {
      imgResult = reader.result
    }
    reader.onerror = function (error) {
      reject(error)
    }
    reader.onloadend = function () {
      resolve(imgResult)
    }
  })
}
const handleRemove = (file, fileList, key) => {
  if (file) {
    form.value[key] = ''
  }
}
defineExpose({ dialogVisible, title })
onMounted(() => {})
</script>
<style lang="scss" scoped>
:deep(.custom-upload) {
  .el-upload--picture-card {
    width: 50px;
    height: 50px;
    border: none;
    background: transparent;
  }
  .el-upload-list__item {
    width: 50px;
    height: 50px;
  }
  .el-button {
    width: 50px;
    height: 50px;
    background: #fafafa;
    color: #409eff;
    border: 1px dashed #cdd0d6;
    border-radius: 6px;
    .el-icon {
      font-size: 20px;
    }
  }
}
:deep(.custom-upload-dark) {
  .el-upload-list__item {
    background: linear-gradient(0deg, #4576ee, #6297f5);
  }
}
</style>
